<template>
	<div class="card-list-container">
		<div class="card-list">
			<div v-for="(card, index) in cardList" :key="index"
				:class="['card', { 'past': isPastDeadline(card.deadline) }]"
				:style="{ backgroundImage: `url(${card.backgroundImage})` }" @click="navigateToDetail(card.tvId)">
				<div class="content">
					<div class="header">
						<div class="title">{{ card.title }}</div>
						<div class="date" :class="{ 'past': isPastDeadline(card.deadline) }">
							{{ card.date }}
						</div>
					</div>
					<div class="body">
						<div class="text">{{ card.text }}</div>
						<button class="signup-button" @click.stop="signup(card.tvId, card.id)"
							:class="{ 'past': isPastDeadline(card.deadline), 'signed-in': card.isSignedIn }">
							{{ card.isSignedIn ? '已签到' : '报名' }}
						</button>
						<button class="qrcode-button" @click.stop="viewQrcode(card.tvId, card.endTime)"
							:class="{ 'past': isPastDeadline(card.deadline), 'signed-in': card.isSignedIn }">查看二维码</button>
					</div>
				</div>
			</div>
		</div>
		<van-pagination v-model:current-page="currentPage" :total-items="totalItems" :items-per-page="itemsPerPage"
			@change="fetchTvList" />
	</div>
</template>

<script>
	import {
		listEnabledTv
	} from '@/api/tv';
	import {
		listSignedInUsers
	} from '@/api/system/audi';

	export default {
		data() {
			return {
				cardList: [],
				currentPage: 1,
				totalItems: 0,
				itemsPerPage: 4,
				loading: true,
				sortBy: 'sort',
				sortDirection: 'ASC'
			};
		},
		methods: {
			async fetchTvList(page = 1) {
				this.loading = true;

				listEnabledTv({
					pageNum: page,
					pageSize: this.itemsPerPage,
					sortBy: this.sortBy,
					sortDirection: this.sortDirection,
					isEnable: 1
				}).then(response => {
					if (response && response.code === 200) {
						const {
							rows,
							total
						} = response;
						this.totalItems = total;

						// 获取当前用户的签到数据
						return listSignedInUsers({
							userId: this.userId // 替换为实际用户ID的获取方法
						}).then(signedInResponse => {
							console.warn(signedInResponse)
							const signedInMap = {}; // 存储每个 tvId 的签到状态的映射
							console.log(signedInResponse);
							console.log('end');
							if (signedInResponse && signedInResponse.code === 200) {
								console.log("开始存数据");
								signedInResponse.data.forEach(entry => {
									console.log("循环");
									signedInMap[entry.tvId] = {
										isSignedIn: entry.isSignedIn,
										signInTime: entry.signInTime,
										signInType: entry.signInType
									};
								});
							}
							console.log(signedInMap);

							// 将 TV 数据映射到 cardList，并包括签到状态
							this.cardList = rows.map(tv => ({
								title: tv.name,
								backgroundImage: tv.cover || 'default-image-url',
								date: this.formatDate(tv.startTime),
								text: tv.info || 'No information available',
								tvId: tv.id,
								id: tv.id,
								deadline: new Date(tv.signupDeadline).getTime(),
								endTime: tv.endTime,
								isSignedIn: signedInMap[tv.id] ? signedInMap[tv.id]
									.isSignedIn : false,
								signInTime: signedInMap[tv.id] ? signedInMap[tv.id]
									.signInTime : null,
								signInType: signedInMap[tv.id] ? signedInMap[tv.id]
									.signInType : null
							}));
						});
					} else {
						console.error('Failed to fetch TV list:', response.msg || 'Unknown error');
					}
				}).catch(error => {
					console.error('Failed to fetch TV list:', error);
				}).finally(() => {
					this.loading = false;
				});
			},

			viewQrcode(tvId, endTime) {
				this.$tab.navigateTo(`/pages/vist/qrcode?tvId=${tvId}&endTime=${endTime}`);
				if (this.isSignedIn(tvId)) {
					console.warn('该用户已经签到过该节目');
				} else {
					console.warn('没签到过.');
				}
			},
			signup(tvId, id) {
				if (this.isSignedIn(tvId)) {
					console.warn('User is already signed in for this TV event.');
				} else {
					this.$tab.navigateTo(`/pages/vist/audi?tvId=${tvId}`);
				}
			},
			isSignedIn(tvId) {
				const tv = this.cardList.find(card => card.tvId === tvId);
				return tv && tv.isSignedIn;
			},
			formatDate(dateStr) {
				const date = new Date(dateStr);
				return `${date.getMonth() + 1}月${date.getDate()}日`;
			},
			navigateToDetail(tvId) {
				this.$tab.navigateTo(`/pages/vist/audi?tvId=${tvId}`);
			},
			isPastDeadline(deadline) {
				return Date.now() > deadline;
			}
		},
		created() {
			this.fetchTvList();
		}
	};
</script>




<style scoped>
	.signed-in {
		background-color: #ccc !important;
		/* 或者你希望的其他颜色 */
		cursor: not-allowed !important;
		color:#000!important;
	}

	.signed-in:hover {
		background-color: #ccc;
		/* 确保悬停时样式不变 */
	}

	.card-list-container {
		padding: 20px;
		background-color: #f0fff0;
	}

	.card-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		align-items: flex-start;
		min-height: 70vh;
	}

	.card {
		position: relative;
		width: calc(100% - 40px);
		max-width: 600px;
		margin: 20px;
		border-radius: 15px;
		overflow: hidden;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		cursor: pointer;
		border: 1px solid #ccc;
		transition: transform 0.3s ease, box-shadow 0.3s ease;
	}

	.card:hover {
		transform: scale(1.05);
		box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
	}

	.card::before {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.4);
	}

	.content {
		position: relative;
		z-index: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 20px;
		color: #fff;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.title {
		font-size: 28rpx;
		font-weight: bold;
		padding: 8px 16px;
		background-color: #b8860b;
		border-top-right-radius: 8px;
		color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
		align-self: flex-start;
		position: relative;
		margin-left: -20px;
	}

	.title::after {
		content: "";
		position: absolute;
		top: -10px;
		right: 0;
		border-width: 10px 0 0 10px;
		border-color: transparent transparent transparent rgba(0, 0, 0, 0.4);
		border-style: solid;
	}

	.date {
		font-size: 13px;
		text-align: right;
		background-color: #39b54a;
		color: #fff;
		padding: 46px 29px 11px 35px;
		border-bottom-left-radius: 8px;
		border-top-right-radius: 8px;
		position: absolute;
		top: 0;
		right: -50px;
		margin: 8px 13px 6px 22px;
		transform: translateY(-50%) rotate(45deg);
		transform-origin: center center;
		z-index: 1;
		line-height: 10px;
	}

	.date span {
		font-size: 20rpx;
		margin-left: 5rpx;
	}

	.body {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 20px;
		padding: 10px;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 8px;
	}

	.text {
		font-size: 24rpx;
		flex: 1;
		color: #fff;
	}

	.signup-button,
	.qrcode-button {
		margin-left: 10px;
		padding: 8px 16px;
		background-color: #39b54a;
		color: #fff;
		text-align: center;
		border: none;
		border-radius: 8px;
		font-size: 20rpx;
		cursor: pointer;
		transition: background-color 0.3s ease;
	}

	.signup-button:hover,
	.qrcode-button:hover {
		background-color: #33a142;
	}

	.past {
		filter: grayscale(100%);
		cursor: not-allowed;
		pointer-events: none;
	}

	.past .signup-button,
	.past .qrcode-button {
		background-color: #ccc;
		cursor: not-allowed;
	}

	.past .date {
		background-color: #999;
	}

	.signed-in {
		background-color: #ccc !important;
		cursor: not-allowed !important;
	}
</style>